﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UploadApi.Controllers
{
    [HandleError]
    public class UploadController : Controller
    {
        [AcceptVerbs(HttpVerbs.Post)]
        public ContentResult Import(HttpPostedFileBase fileData, string folder)
        {
            var result = string.Empty;
            if (fileData != null)
            {
                try
                {
                    //获得文件名 
                    result = Path.GetFileName(fileData.FileName);

                    //获得文件扩展名            
                    var ext = Path.GetExtension(fileData.FileName);

                    //实际保存文件名            
                    var saveName = "uploadfile" + ext;

                    //保存文件   
                    SaveFile(fileData, folder, result);

                    result = "http://" + Request.Url.Authority + folder + "/" + result;
                }
                catch
                {
                    result = string.Empty;
                }
            }
            return Content(result);
        }

        [NonAction]
        private void SaveFile(HttpPostedFileBase postedFile, string filepath, string saveName)
        {
            var phyPath = Request.MapPath("~" + filepath + "/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }
    }
}
